use std::time::Duration;

use tokio::sync::oneshot;

use crate::p2p::{
    client::main::Client, mode::command::Command, types::common::TResult, utils::error::comm_err,
};

impl Client {
    pub async fn stop(&mut self, timeout: Option<Duration>) -> TResult {
        let (sender, receiver) = oneshot::channel();
        let _ = self.send_command(Command::Stop { sender });
        tokio::select! {
            result = receiver => match result{
                Ok(result) => result,
                Err(_) => Err(comm_err("Failed to stop the client")),
            },
            _ = tokio::time::sleep(timeout.unwrap_or(self.timeout)) => Err(comm_err( "Failed to stop the client")),
        }
    }
}
